package com.twu.biblioteca.model.users;

import com.twu.biblioteca.model.users.exceptions.InvalidUsernameException; /**
 * Created with IntelliJ IDEA.
 * User: cschlumb
 * Date: 12/08/2013
 * Time: 16:08
 * To change this template use File | Settings | File Templates.
 */
public class Username {

    private static int counter = 111111;
    private final int id;

    public Username() {
        id = counter++;
    }

    private Username(int id){
        this.id = id;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Username username = (Username) o;

        if (id != username.id) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return id;
    }

    public static Username valueOf(String id) throws InvalidUsernameException {
        if (! id.matches("[1-9]{4}-[1-9]{4}"))
            throw new InvalidUsernameException();

        int integer = Integer.valueOf(id.replaceAll("-", ""));
        return new Username(integer);
    }

    public static Username valueOf(int id){
        return new Username(id);
    }

    @Override
    public String toString() {
        char[] charArray = String.valueOf(id).toCharArray();

        StringBuilder sb = new StringBuilder();

        sb.append(charArray, 0, 4);
        sb.append('-');
        sb.append(charArray, 4, 4);

        return sb.toString();
    }
}
